package com.project.slsx.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.request.target.ThumbnailImageViewTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.project.slsx.Constant.Constans;
import com.project.slsx.R;
import com.project.slsx.adapter.MultiTypeAdapter;
import com.project.slsx.adapter.ReaultAdapter;
import com.project.slsx.adapter.CategoryAdapter;
import com.project.slsx.adapter.ShopCartAdapter;
import com.project.slsx.bean.CashGoodsListBean;
import com.project.slsx.bean.GoodsBean;
import com.project.slsx.bean.GuaDanBean;
import com.project.slsx.bean.ResultBean;
import com.project.slsx.utils.DialogUtils;
import com.project.slsx.utils.ParamsUtils;
import com.project.slsx.utils.SPUtils;
import com.project.slsx.widget.EditInputFilter;
import com.project.slsx.widget.MyPopupWindow;
import com.project.slsx.widget.dialog.BaseNiceDialog;
import com.project.slsx.widget.dialog.ViewConvertListener;
import com.project.slsx.widget.dialog.ViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.MoveType;
import com.yhao.floatwindow.Screen;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CashActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = CashActivity.class.getSimpleName();
    private RecyclerView left;
    private RecyclerView right;
    private CategoryAdapter categoryAdapter;
    private ReaultAdapter resultAdapter;
    private ShopCartAdapter cartAdapter;
    private int page = 1;
    private int pageSize = 20;
    private String bindCode = "";//绑定条形码
    private CashGoodsListBean.ResultBean resultBean;
    private ArrayList<Boolean> selected;
    private ArrayList<Boolean> shopCartItemSelected;
    private TextView tvCartTotalMoney;
    private TextView tvCartNumber;
    private RecyclerView rvShopCart;
    private int cartItemSelected = -1;
    private MyPopupWindow myPopupWindow;
    private int cartDialogNumber = 0;
    private String cartDialogPercent = "100";
    private String cartDialogTotalPrice = "";
    private SmartRefreshLayout sfl;
    private String categoryId;//分类id
    private TextView tvWsc;
    private TextView tvMt;
    private TextView tvElm;
    private EditText edSearch;
    private ImageView ivSearch;
    private String searchStr;//搜索
    private TextView tvGuadanNum;
    private int onClickPosition = 0;
    private CashGoodsListBean.ResultBean.OptionsBean selectenOptionId;
    private String edZJTotalStr = "";//结账弹窗总金额
    private TextView tvZhaoling;
    private TextView tvZengsong;
    private TextView tvCash;
    private TextView tvTotal;
    private String amount;//购物车总金额
    private List<CashGoodsListBean.ResultBean.OptionsBean> singleOptions;
    private int times100 = 0;
    private int times50 = 0;
    private int times20 = 0;
    private int times10 = 0;
    private TextView tvCartClear;
    private EditText edJz;


    @Override
    public int getLayoutId() {
        return R.layout.activity_cash;
    }

    @Override
    public void initView() {
        TextView all = findViewById(R.id.t_cash_category_all);
        all.setOnClickListener(this);
        sfl = findViewById(R.id.sfl);
        ivSearch = findViewById(R.id.iv_shop_cart_search);
        edSearch = findViewById(R.id.ed_shop_cart_search);
        tvCartNumber = findViewById(R.id.tv_cash_shop_cart_num);
        tvCartTotalMoney = findViewById(R.id.tv_cash_shop_cart_money);
        tvCartClear = findViewById(R.id.tv_shopcart_clear);
        tvWsc = findViewById(R.id.tv_wx);
        tvMt = findViewById(R.id.tv_mt);
        tvElm = findViewById(R.id.tv_elm);
        findViewById(R.id.rl_back).setOnClickListener(v -> finish());
        TextView tvRight = findViewById(R.id.tv_right);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setOnClickListener(this);
        left = findViewById(R.id.recyclerview_cash_left);
        left.setLayoutManager(new GridLayoutManager(this, 4));
        resultAdapter = new ReaultAdapter(R.layout.layout_item_cash_left);
        left.setHasFixedSize(true);
        left.setAdapter(resultAdapter);


        right = findViewById(R.id.recyclerview_cash_right);
        right.setLayoutManager(new LinearLayoutManager(this));
        categoryAdapter = new CategoryAdapter(R.layout.layout_item_cash_right);
        right.setAdapter(categoryAdapter);

        rvShopCart = findViewById(R.id.rv_shop_cart);
        rvShopCart.setLayoutManager(new LinearLayoutManager(this));
        cartAdapter = new ShopCartAdapter(R.layout.layout_item_shop_cart);
        rvShopCart.setAdapter(cartAdapter);

        findViewById(R.id.btn_cash_jiezhang).setOnClickListener(this);
        findViewById(R.id.btn_cash_guadan).setOnClickListener(this);

        cartAdapter.setOnItemClickListener((adapter, view, position) -> {
            Log.i(TAG, "initView: " + position);
            cartItemSelected = position;
            setShopCartItemBg(shopCartItemSelected, position);

            myPopupWindow = new MyPopupWindow(mContext);
            View contentView = myPopupWindow.getContentView();
            Button btnZS = contentView.findViewById(R.id.btn_shop_cart_zengsong);//赠送
            btnZS.setOnClickListener(this);
            Button btnDZ = contentView.findViewById(R.id.btn_shop_cart_dazhe);//打折
            btnDZ.setOnClickListener(this);
            Button btnSC = contentView.findViewById(R.id.btn_shop_cart_shanchu);//删除
            btnSC.setOnClickListener(this);
            myPopupWindow.setWidth(view.getWidth());
            myPopupWindow.setHeight(view.getHeight());
            PopupWindowCompat.showAsDropDown(myPopupWindow, view, 0, 0, Gravity.START);
        });

        //种类
        categoryAdapter.setOnItemClickListener((adapter, view, position) -> {
            List<CashGoodsListBean.CategoryBean> data = adapter.getData();
            categoryId = data.get(position).getId();
            setSelected(adapter, position);
            searchStr = "";
            sfl.autoRefresh();
//            getGoodsById(false,categoryId);
        });

        //点击添加到购物车
        resultAdapter.setOnItemClickListener((adapter, view, position) -> {
            onClickPosition = position;
            CashGoodsListBean.ResultBean selectedBean = (CashGoodsListBean.ResultBean) adapter.getData().get(onClickPosition);
            singleOptions = selectedBean.getOptions();
            if (selectedBean.getIs_other() == 1) {
                showToast(mContext, "临时商品");
            } else {
                if (singleOptions.size() > 0) {
                    DialogUtils.showDialog(R.layout.dialog_mutli_type, 500, 300, true,
                            singleListener, getSupportFragmentManager());
                } else {
                    addToShopCart(true);
                }
            }

        });

        resultAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            onClickPosition = position;
            resultBean = (CashGoodsListBean.ResultBean) adapter.getData().get(position);
            List<CashGoodsListBean.ResultBean.OptionsBean> options = resultBean.getOptions();
            if (resultBean.getIs_other() == 1) {
                showToast(mContext, "临时商品");
            } else {
                if (options.size() > 0) {
                    DialogUtils.showDialog(R.layout.dialog_mutli_type, 500, 300, true,
                            mutilListener, getSupportFragmentManager());
                } else {
                    DialogUtils.showDialog(R.layout.dialog_bind, 300, 300, true,
                            bindListener, getSupportFragmentManager());
                }
            }
            return true;
        });
    }

    /**
     * 点击 添加到购物车
     */
    private void addToShopCart(boolean isClick) {
        shopCartItemSelected.clear();
        CashGoodsListBean.ResultBean resultBean = resultAdapter.getData().get(onClickPosition);
        int selectedGoodsIndex = 0;//添加选中商品的index
        boolean hasSameGoods = false;
        GoodsBean goodsBean = new GoodsBean();
        //点击
        if (isClick) {
            goodsBean.setTitle(resultBean.getTitle());
            goodsBean.setNumber(1);
            goodsBean.setGoods_id(resultBean.getId());
            goodsBean.setPrice(Double.valueOf(resultBean.getPrice()));
            goodsBean.setZengsong(false);
            goodsBean.setOption_id(resultBean.getOptions().size() == 0 ? "0" : resultBean.getOptions().get(0).getGoods_id());
            goodsBean.setDiscount(100);
        } else {
            //长按 选中规格之后
            goodsBean.setTitle(selectenOptionId.getName());
            goodsBean.setNumber(1);
            goodsBean.setGoods_id(selectenOptionId.getId());
            goodsBean.setPrice(Double.valueOf(selectenOptionId.getPrice()));
            goodsBean.setZengsong(false);
            goodsBean.setOption_id(selectenOptionId.getGoods_id());
            goodsBean.setDiscount(100);
        }
        //购物车数量
        List<GoodsBean> data = cartAdapter.getData();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getGoods_id().equals(isClick ? resultBean.getId() : selectenOptionId.getId())) {
                selectedGoodsIndex = i;
                hasSameGoods = true;
                data.get(i).setNumber(data.get(i).getNumber() + 1);
                cartAdapter.notifyDataSetChanged();
            }
        }
        //用来确定添加商品的index
        if (!hasSameGoods) {
            selectedGoodsIndex = data.size();
            cartAdapter.addData(goodsBean);
        }
        //记录购物车条目选中
        for (int i = 0; i < data.size(); i++) {
            shopCartItemSelected.add(false);
        }
        for (int i = 0; i < data.size(); i++) {
            if (i == selectedGoodsIndex) {
                shopCartItemSelected.set(i, true);
            } else {
                shopCartItemSelected.set(i, false);
            }
        }
        //设置购物车条目选中背景
        cartAdapter.setSelectedItem(shopCartItemSelected);
        rvShopCart.smoothScrollToPosition(selectedGoodsIndex);
        String[] totalMoneyAndNumber = getTotalMoneyAndNumber();
        tvCartNumber.setText(totalMoneyAndNumber[0]);
        tvCartTotalMoney.setText(totalMoneyAndNumber[1]);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
        String string = SPUtils.getInstance().getString(Constans.GUADAN, "");
        if (!TextUtils.isEmpty(string)) {
            GuaDanBean guaDanBean = JSONObject.parseObject(string, GuaDanBean.class);
            List<List<GoodsBean>> guadanList = guaDanBean.getGuadanList();
            tvGuadanNum.setText(String.valueOf(guadanList.size()));
        }
    }

    @Override
    public void initData() {
        //记录右边item是否被选中
        selected = new ArrayList<>();
        //购物车列表
        shopCartItemSelected = new ArrayList<>();
        sfl.autoRefresh();
        sfl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                refreshLayout(false, refreshLayout);
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                refreshLayout(true, refreshLayout);
            }
        });
        ivSearch.setOnClickListener(this);
        edSearch.addTextChangedListener(new MySearchWatcher());
        //悬浮球
        View floatview = View.inflate(mContext, R.layout.floatview, null);
        FloatWindow
                .with(getApplicationContext())
                .setView(floatview)
                .setWidth(60)                               //设置控件宽高
                .setHeight(60)
                .setX(10)                                   //设置控件初始位置
                .setY(Screen.height, 0.6f)
                .setFilter(true, CashActivity.class)
                .setDesktopShow(true)                        //桌面显示
                .setMoveType(MoveType.slide)
                .setTag("shop")
                .setMoveStyle(500, new AccelerateInterpolator())  //贴边动画时长为500ms，加速插值器
//                .setViewStateListener(mViewStateListener)    //监听悬浮控件状态改变
//                .setPermissionListener(mPermissionListener)  //监听权限申请结果
                .build();
        RelativeLayout windowview = (RelativeLayout) FloatWindow.get("shop").getView();
        tvGuadanNum = windowview.findViewById(R.id.tv_guadan_number);
        windowview.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, GuadanDetailActivity.class);
            startActivityForResult(intent, 1001);
        });
        tvCartClear.setOnClickListener(this);
    }

    private void refreshLayout(boolean b, RefreshLayout refreshLayout) {
        refreshLayout.getLayout().postDelayed(() -> {
            //true 下拉刷新 false 上啦加载更多
            if (b) {
                page = 1;
                sfl.setEnableLoadMore(false);
                Log.i(TAG, "refreshLayout: " + " refrsh data" + page);
            } else {
                ++page;
                Log.i(TAG, "refreshLayout: " + " load more" + page);
            }
//            if (TextUtils.isEmpty(categoryId)) {
//                getGoodsList(b);
//            }else {
//                getGoodsById(b,categoryId);
//            }

            getGoodsList(b);
        }, 50);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_shop_cart_search:
                categoryId = "";
                searchStr = edSearch.getText().toString().trim();
                sfl.autoRefresh();
                break;
            case R.id.t_cash_category_all:
                categoryId = "";
                sfl.autoRefresh();
                break;
            case R.id.btn_cash_guadan:
                List<GoodsBean> guadanList = cartAdapter.getData();
                if (guadanList.size() == 0) {
                    showToast(mContext, "请先添加商品");
                } else {
                    DialogUtils.showDialog(R.layout.dialog_guadan, 260, 180, true, guadanListener,
                            getSupportFragmentManager());
                }
                break;
            case R.id.btn_cash_jiezhang:
//                doOrderAdd();
                edZJTotalStr = "";
                DialogUtils.showDialog(R.layout.dialog_jianpan, 500, 500, true, jianpanListener,
                        getSupportFragmentManager());
                break;

            case R.id.btn_shop_cart_zengsong:
                List<GoodsBean> data = cartAdapter.getData();
                data.get(cartItemSelected).setDiscount(0);
//                data.get(cartItemSelected).setPrice(0);
                data.get(cartItemSelected).setSumPrice(0);
                data.get(cartItemSelected).setZengsong(true);
                cartAdapter.notifyItemChanged(cartItemSelected);
                String[] totalMoneyAndNumber = getTotalMoneyAndNumber();
                tvCartNumber.setText(totalMoneyAndNumber[0]);
                tvCartTotalMoney.setText(totalMoneyAndNumber[1]);
                break;

            case R.id.btn_shop_cart_dazhe:
                DialogUtils.showDialog(R.layout.dialog_discount, 360, 260,
                        true, discountListener, getSupportFragmentManager());
                break;

            case R.id.btn_shop_cart_shanchu:
                List<GoodsBean> resultData = cartAdapter.getData();
                resultData.remove(cartItemSelected);
                cartAdapter.setNewData(resultData);
                if (myPopupWindow != null && myPopupWindow.isShowing()) {
                    myPopupWindow.dismiss();
                }
                break;

            case R.id.tv_right:
                startActivity(new Intent(mContext, StorageActivity.class));
                break;
            case R.id.tv_shopcart_clear:
                cartAdapter.setNewData(null);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001) {
            if (resultCode == RESULT_OK) {
                int intExtra = data.getIntExtra(Constans.RESULT, 0);
                String string = SPUtils.getInstance().getString(Constans.GUADAN, "");
                if (!TextUtils.isEmpty(string)) {
                    GuaDanBean guaDanBean = JSONObject.parseObject(string, GuaDanBean.class);
                    List<GoodsBean> goodsBeans = guaDanBean.getGuadanList().get(intExtra);

                    shopCartItemSelected.clear();
                    for (int i = 0; i < goodsBeans.size(); i++) {
                        if (i == 0) {
                            shopCartItemSelected.add(true);
                        } else {
                            shopCartItemSelected.add(false);
                        }
                    }
                    cartAdapter.setSelectedItem(shopCartItemSelected);
                    cartAdapter.setNewData(goodsBeans);
                }
                Log.i(TAG, "onActivityResult: " + intExtra);
            }
        }
    }

    /**
     * 计算购物车 总价 总数
     */
    private String[] getTotalMoneyAndNumber() {
        int sumNumber = 0;
        double sumMoney = 0;
        List<GoodsBean> data = cartAdapter.getData();
        if (data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                GoodsBean goodsBean = data.get(i);
                sumMoney += goodsBean.isZengsong() ? 0 : goodsBean.getNumber() * data.get(i).getPrice();
                sumNumber += data.get(i).getNumber();
            }
        }
        String[] result = {String.valueOf(sumNumber), String.valueOf(sumMoney)};
        return result;
    }

    private void setSelected(BaseQuickAdapter adapter, int position) {
        for (int i = 0; i < adapter.getData().size(); i++) {
            if (i == position) {
                categoryAdapter.getSelected().set(i, true);
            } else {
                categoryAdapter.getSelected().set(i, false);
            }
            categoryAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 购物车点击设置背景
     *
     * @param shopCartItemSelected
     * @param position
     */
    private void setShopCartItemBg(ArrayList<Boolean> shopCartItemSelected, int position) {
        int size = shopCartItemSelected.size();
        for (int i = 0; i < size; i++) {
            if (i == position) {
                shopCartItemSelected.set(i, true);
            } else {
                shopCartItemSelected.set(i, false);
            }
        }
        cartAdapter.setSelectedItem(shopCartItemSelected);
    }

    /**
     * 绑定条码
     */
    private ViewConvertListener bindListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            LinearLayout discountView = (LinearLayout) holder.getConvertView();
            discountView.findViewById(R.id.btn_open_cancel).setOnClickListener(v -> DialogUtils.dissmissDialog());
            EditText edBarcode = discountView.findViewById(R.id.ed_barcode);
            edBarcode.addTextChangedListener(new MyWatcher());
            discountView.findViewById(R.id.btn_open_ok).setOnClickListener(v -> {
                Log.i(TAG, "convertView: ");
                if (TextUtils.isEmpty(bindCode)) {
                    showToast(mContext, "请输入条商品条码");
                    return;
                }
                doBindBarcode();
            });
        }
    };

    /**
     * 单规格商品
     */
    private ViewConvertListener singleListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            LinearLayout mutilView = (LinearLayout) holder.getConvertView();
            RecyclerView recyclerView = mutilView.findViewById(R.id.recyclervew_mutli);
            recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
            MultiTypeAdapter adapter = new MultiTypeAdapter(R.layout.layout_item_multi_type);
            recyclerView.setAdapter(adapter);
            adapter.setNewData(singleOptions);
            adapter.setOnItemClickListener((adapter1, view, position) -> {
                List data = adapter1.getData();
                selectenOptionId = (CashGoodsListBean.ResultBean.OptionsBean) data.get(position);
                addToShopCart(false);
                DialogUtils.dissmissDialog();
                Log.i(TAG, "convertView: " + position);
            });
        }
    };
    /**
     * 多规格商品
     */
    private ViewConvertListener mutilListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            LinearLayout mutilView = (LinearLayout) holder.getConvertView();
            RecyclerView recyclerView = mutilView.findViewById(R.id.recyclervew_mutli);
            recyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
            MultiTypeAdapter adapter = new MultiTypeAdapter(R.layout.layout_item_multi_type);
            recyclerView.setAdapter(adapter);
            List<CashGoodsListBean.ResultBean.OptionsBean> options = resultBean.getOptions();
            adapter.setNewData(options);
            adapter.setOnItemClickListener((adapter1, view, position) -> {
                List data = adapter1.getData();
                selectenOptionId = (CashGoodsListBean.ResultBean.OptionsBean) data.get(position);
                addToShopCart(false);
                DialogUtils.dissmissDialog();
                Log.i(TAG, "convertView: " + position);
            });
        }
    };

    /**
     * 挂单列表
     */

    private ViewConvertListener guadanListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            List<GoodsBean> data = cartAdapter.getData();
            LinearLayout convertView = (LinearLayout) holder.getConvertView();
            convertView.findViewById(R.id.btn_guadan_cancel).setOnClickListener(v -> {
                DialogUtils.dissmissDialog();
            });
            convertView.findViewById(R.id.btn_guadan_ok).setOnClickListener(v -> {
                String string = SPUtils.getInstance().getString(Constans.GUADAN, "");
                if (TextUtils.isEmpty(string)) {
                    GuaDanBean guaDanBean = new GuaDanBean();
                    guaDanBean.getGuadanList().add(data);
                    String s = JSONObject.toJSONString(guaDanBean);
                    tvGuadanNum.setText(String.valueOf(1));
                    SPUtils.getInstance().put(Constans.GUADAN, s);
                } else {
                    GuaDanBean guaDanBean = JSONObject.parseObject(string, GuaDanBean.class);
                    guaDanBean.getGuadanList().add(data);
                    if (guaDanBean.getGuadanList() != null && guaDanBean.getGuadanList().size() > 0) {
                        //挂单数量
                        int guadanSize = guaDanBean.getGuadanList().size();
                        tvGuadanNum.setText(String.valueOf(guadanSize));
                        cartAdapter.setNewData(null);
                        DialogUtils.dissmissDialog();
                        Log.i(TAG, "onClick: " + guaDanBean.getGuadanList().size());
                    }
                    String reslutList = JSONObject.toJSONString(guaDanBean);
                    SPUtils.getInstance().put(Constans.GUADAN, reslutList);
                }

                showToast(mContext, "成功添加到挂单列表");
                dialog.dismiss();
            });
        }
    };

    /**
     * 键盘
     */
    private ViewConvertListener jianpanListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            //商品总价格
            amount = getTotalMoneyAndNumber()[1];
            LinearLayout convertView = (LinearLayout) holder.getConvertView();
            edJz = convertView.findViewById(R.id.ed_zj_cash);
            edJz.addTextChangedListener(new MyJzWatcher(edJz,amount));
            //总金额
            tvTotal = convertView.findViewById(R.id.tv_jz_total);
            //现金
            tvCash = convertView.findViewById(R.id.tv_jz_cash);
            //找零
            tvZhaoling = convertView.findViewById(R.id.tv_jz_zhaoling);
            //赠送
            tvZengsong = convertView.findViewById(R.id.tv_zj_zengsong);
            tvTotal.setText(amount);

            convertView.findViewById(R.id.btn_jz_100).setOnClickListener(v -> {
                double current = 0;
                if (Double.valueOf(amount) > 100) {
                    return;
                }
                String s = edJz.getText().toString().trim();
                if (TextUtils.isEmpty(s)) {
                    current = 100;
                    edJz.setText(String.valueOf(current));
                } else {
                    String trim = edJz.getText().toString().trim();
                    double result = Double.valueOf(trim) + 100;
                    edJz.setText(String.valueOf(result));
                }
            });
            convertView.findViewById(R.id.btn_jz_50).setOnClickListener(v -> {
                double current = 0;
                if (Double.valueOf(amount) > 50) {
                    return;
                }
                String s = edJz.getText().toString().trim();
                if (TextUtils.isEmpty(s)) {
                    current = 50;
                    edJz.setText(String.valueOf(current));
                } else {
                    String trim = edJz.getText().toString().trim();
                    double result = Double.valueOf(trim) + 50;
                    edJz.setText(String.valueOf(result));
                }
            });
            convertView.findViewById(R.id.btn_jz_20).setOnClickListener(v -> {
                double current = 0;
                if (Double.valueOf(amount) > 20) {
                    return;
                }
                String s = edJz.getText().toString().trim();
                if (TextUtils.isEmpty(s)) {
                    current = 20;
                    edJz.setText(String.valueOf(current));
                } else {
                    String trim = edJz.getText().toString().trim();
                    double result = Double.valueOf(trim) + 20;
                    edJz.setText(String.valueOf(result));
                }
            });
            convertView.findViewById(R.id.btn_jz_10).setOnClickListener(v -> {
                double current = 0;
                if (Double.valueOf(amount) > 10) {
                    return;
                }
                String s = edJz.getText().toString().trim();
                if (TextUtils.isEmpty(s)) {
                    current = 10;
                    edJz.setText(String.valueOf(current));
                } else {
                    String trim = edJz.getText().toString().trim();
                    double result = Double.valueOf(trim) + 10;
                    edJz.setText(String.valueOf(result));
                }
            });
            convertView.findViewById(R.id.btn_jz_0).setOnClickListener(v -> {
                edZJTotalStr = "0";
                edJz.setText(edZJTotalStr);
                edJz.setSelection(edZJTotalStr.length());
            });
            convertView.findViewById(R.id.btn_jz_1).setOnClickListener(v -> {
                setKeyboard(edJz, 1);
            });
            convertView.findViewById(R.id.btn_jz_2).setOnClickListener(v -> {
                setKeyboard(edJz, 2);
            });
            convertView.findViewById(R.id.btn_jz_3).setOnClickListener(v -> {
                setKeyboard(edJz, 3);
            });
            convertView.findViewById(R.id.btn_jz_4).setOnClickListener(v -> {
                setKeyboard(edJz, 4);
            });
            convertView.findViewById(R.id.btn_jz_5).setOnClickListener(v -> {
                setKeyboard(edJz, 5);
            });
            convertView.findViewById(R.id.btn_jz_6).setOnClickListener(v -> {
                setKeyboard(edJz, 6);
            });
            convertView.findViewById(R.id.btn_jz_7).setOnClickListener(v -> {
                setKeyboard(edJz, 7);
            });
            convertView.findViewById(R.id.btn_jz_8).setOnClickListener(v -> {
                setKeyboard(edJz, 8);
            });
            convertView.findViewById(R.id.btn_jz_9).setOnClickListener(v -> {
                setKeyboard(edJz, 9);
            });
            convertView.findViewById(R.id.btn_jz_dot).setOnClickListener(v -> {
                String trim = edJz.getText().toString().trim();
                if (edJz.getText().toString().trim().contains(".")) {
                    return;
                }

                if (trim.contains(".") && trim.split(".")[1].length() > 1) {
                    Log.i(TAG, "convertView: ");
                    return;
                }

                if (!TextUtils.isEmpty(edZJTotalStr) && !edZJTotalStr.startsWith(".")) {
                    edZJTotalStr += ".";
                    edJz.setText(edZJTotalStr);
                    edJz.setSelection(edZJTotalStr.length());
                }
            });
            convertView.findViewById(R.id.btn_jz_delete).setOnClickListener(v -> {
                edZJTotalStr = "";
                edJz.setText(edZJTotalStr);
                edJz.setSelection(edZJTotalStr.length());
            });
            convertView.findViewById(R.id.btn_jz_cancel).setOnClickListener(v -> {
                DialogUtils.dissmissDialog();
            });
            convertView.findViewById(R.id.btn_jz_cash).setOnClickListener(v -> {
                doOrderAdd(1);
            });

            convertView.findViewById(R.id.btn_jz_saoma).setOnClickListener(v -> {
                doOrderAdd(2);
            });
        }

        private void setKeyboard(EditText edJz, int i) {
            String result;
            String trim = edJz.getText().toString().trim();
            result = trim + i;
            edJz.setText(result);
            edJz.setSelection(result.length());
        }
    };

    /**
     * 获取商品列表
     *
     * @param b
     */
    private void getGoodsList(boolean b) {
        HttpParams goodslistParams = ParamsUtils.getGoodslistParams();
        goodslistParams.put("category_id", categoryId);
        goodslistParams.put("keyword", searchStr);
        goodslistParams.put("page", page);
        goodslistParams.put("page_size", pageSize);
        OkGo.<String>post(Constans.BASEURL).tag("goodslist").params(goodslistParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
                CashGoodsListBean cashGoodsListBean = JSONObject.parseObject(response.body(), CashGoodsListBean.class);
                if (cashGoodsListBean != null) {
                    if (cashGoodsListBean.getErrno() == Constans.SUCCESS) {
                        showToast(mContext, cashGoodsListBean.getErrmsg());
                        setWxMtElm(cashGoodsListBean.getWeixin(), cashGoodsListBean.getMeituan(), cashGoodsListBean.getEleme());
                        List<CashGoodsListBean.CategoryBean> category = cashGoodsListBean.getCategory();
                        List<CashGoodsListBean.ResultBean> result = cashGoodsListBean.getResult();
                        for (int i = 0; i < category.size(); i++) {
//                            if (i == 0) {
//                                selected.add(true);
//                            } else {
                            selected.add(false);
//                            }
                        }
                        categoryAdapter.setSelect(selected);
                        if (result.size() > 0) {
                            if (b) {
                                if (category.size() > 0) {
                                    categoryAdapter.setNewData(category);
                                }
                                resultAdapter.setNewData(result);
                            } else {
                                resultAdapter.addData(result);
                            }
                        } else {
                            showToast(mContext, "无更多商品");
                        }
                    } else {
                        showToast(mContext, "无数据");
                    }
                } else {
                    showToast(mContext, "无数据");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Log.i(TAG, "onError: " + response);
                showToast(mContext, "网络错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (b) {
                    sfl.finishRefresh();
                    sfl.setEnableLoadMore(true);
                } else {
                    sfl.finishLoadMore();
                }
            }
        });
    }

    /**
     * 微商城 美团 饿了么
     *
     * @param weixin
     * @param meituan
     * @param eleme
     */
    private void setWxMtElm(String weixin, String meituan, String eleme) {
        tvWsc.setText(weixin);
        tvMt.setText(meituan);
        tvElm.setText(eleme);
    }

    /**
     * 绑定商品条码
     */
    private void doBindBarcode() {
        HttpParams goodsbindParams = ParamsUtils.getGoodsbindParams();
//        String barcode = "6935284455595";
        goodsbindParams.put("barcode", bindCode);//条形码
        goodsbindParams.put("goods_id", resultBean.getId());//商品id
        goodsbindParams.put("option_id", "");//商品小规格id
        OkGo.<String>post(Constans.BASEURL).tag("goodsbind").params(goodsbindParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                ResultBean resultBean = JSONObject.parseObject(response.body(), ResultBean.class);
                addToShopCart(true);
                showToast(mContext, resultBean.getErrmsg());
                if (resultBean.getErrno() == Constans.SUCCESS) {
                    DialogUtils.dissmissDialog();
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Log.i(TAG, "onError: ");
                showToast(mContext, "网络错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                Log.i(TAG, "onFinish: ");
            }
        });
    }

    /**
     * 结账
     */
    private void doOrderAdd(int type) {
        HttpParams orderaddParams = ParamsUtils.getOrderaddParams();
        List<GoodsBean> data = cartAdapter.getData();
        orderaddParams.put("goods", JSONObject.toJSONString(data));
        orderaddParams.put("type", type);
        OkGo.<String>post(Constans.BASEURL).tag("orderadd").params(orderaddParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    private class MyWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            bindCode = s.toString().trim();
        }
    }

    private class NumberTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            cartDialogNumber = Integer.valueOf(s.toString().trim());
        }
    }

    private class PercentTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            cartDialogPercent = s.toString().trim();
        }
    }

    private class TotalPriceTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            cartDialogTotalPrice = s.toString().trim();
        }
    }

    private class MySearchWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            searchStr = s.toString().trim();
        }
    }

    //结账总金额
    private class MyJzWatcher implements TextWatcher {
        private EditText editText;
        private int digits = 2;

        public MyJzWatcher(EditText et,String amount) {
            editText = et;
            this.amount = amount;
        }

        public MyJzWatcher setDigits(int d) {
            digits = d;
            return this;
        }

        private String amount;


        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            edZJTotalStr = s.toString().trim();
            if (!TextUtils.isEmpty(edZJTotalStr) && !edZJTotalStr.startsWith(".")) {
                double money = Double.valueOf(edZJTotalStr);
                if (money >= Double.valueOf(amount)) {
                    double zhaoling = money - Double.valueOf(amount);
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    String result = String.valueOf(decimalFormat.format(zhaoling));
                    if (result.startsWith(".")) {
                        result = "0" + result;
                    }
                    tvCash.setText(edZJTotalStr);
                    tvZhaoling.setText(result);
                }
            }
        }
    }

    /**
     * 打折dialog
     */
    private ViewConvertListener discountListener = new ViewConvertListener() {
        @Override
        protected void convertView(ViewHolder holder, BaseNiceDialog dialog) {
            GoodsBean goodsBean = cartAdapter.getData().get(cartItemSelected);
            LinearLayout convertView = (LinearLayout) holder.getConvertView();
            TextView originPrice = convertView.findViewById(R.id.tv_shopcart_disconut_price);
            EditText number = convertView.findViewById(R.id.ed_shopcart_disconut_number);
            EditText percent = convertView.findViewById(R.id.ed_shopcart_disconut_percent);
            EditText totalPrice = convertView.findViewById(R.id.ed_shopcart_disconut_total_price);
            Button commit = convertView.findViewById(R.id.btn_shopcart_dialog_ok);

            originPrice.setText(String.valueOf(goodsBean.getPrice()));
            number.addTextChangedListener(new NumberTextWatcher());
            percent.addTextChangedListener(new PercentTextWatcher());
            totalPrice.addTextChangedListener(new TotalPriceTextWatcher());
            commit.setOnClickListener(v -> {
                Log.i(TAG, "convertView: ");
            });
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        FloatWindow.destroy("shop");
    }
}
